#include "tcp.h"
#include "function.h"
/*
#define USER 100
int clients_list[USER] = {0};
int clientSum = 0;
*/

int tcpinit(u_int16_t port,const char* ip){
    int listenfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(port);
    serveraddr.sin_addr.s_addr=inet_addr(ip);
    int ret = bind(listenfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
    ERROR_CHECK(ret,-1,"bind");
    return listenfd;
}

void epollinit(int epfd,int fd){
    struct epoll_event evt;
    evt.data.fd=fd;
    evt.events=EPOLLIN;
    int ret = epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&evt);
    ERROR_CHECK(ret,-1,"epoll_ctl");
}

void pthreadpollinit(pthreadpoll_t pthreadpoll[]) {
	for (int i = 0; i < MAXEVENTS; i++) {
		pthread_t pid;
		pthreadpoll[i].flag = 0;
		pthreadpoll[i].clientfd = -1;
		pthread_mutexattr_t mutexattr;
		pthread_mutexattr_init(&mutexattr);
		pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_TIMED_NP);
		pthread_mutex_init(&pthreadpoll[i].mutex, &mutexattr);
		pthread_cond_init(&pthreadpoll[i].cond, NULL);
		pthread_create(&pid, NULL, waitfunc, &pthreadpoll[i]);
	}
}

void dowork(pthreadpoll_t pthreadpoll[], int clientfd, char * filename, char* order, int epfd, MYSQL * conn) {
	int i = 0;
	for ( ; i < MAXEVENTS; i++) {
		if (pthreadpoll[i].flag == 0) {
			pthreadpoll[i].flag = 1;
			pthreadpoll[i].clientfd = clientfd;
			pthreadpoll[i].order = order;
			pthreadpoll[i].filename = filename;
			pthreadpoll[i].epfd = epfd;
			pthreadpoll[i].conn = conn;
			pthread_cond_signal(&pthreadpoll[i].cond);
			return;
		}
	}
	if (i == MAXEVENTS)
	{
		pthread_t pid_plus;
		pthreadpoll_t pthreadpoll_plus;
		pthread_mutexattr_t mutexattr;
		pthread_mutexattr_init(&mutexattr);
		pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_TIMED_NP);
		pthread_mutex_init(&pthreadpoll_plus.mutex, &mutexattr);
		pthread_cond_init(&pthreadpoll_plus.cond, NULL);
		pthread_create(&pid_plus, NULL, waitfunc, &pthreadpoll_plus);
		pthread_cond_signal(&pthreadpoll_plus.cond);
	}
}